package bhwz.seac3.ui.admin;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JButton;

import bhwz.seac3.LocalBLServiceManager;
import bhwz.seac3.blservice.import_.ErrorLogPrinter;
import bhwz.seac3.ui.user.UserMainFrame;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ServerMainFrame extends JFrame {

	private static final long serialVersionUID = 5151828085136423441L;
	private final String iconPath = "/picture/TrayIcon.png";
	private JPanel contentPane;
	private JTextField isServingTF;
	private SystemTray st;
	private ErrorLogPrinterImpl elp;

	private class ErrorLogPrinterImpl extends JTextArea implements
			ErrorLogPrinter {

		private static final long serialVersionUID = 4081347447630643945L;
		{
			this.setText("Log :\n");
			this.setEditable(false);
		}

		@Override
		public void print(String error) {
			this.append(error + "\n");
		}

	}
////
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					ServerMainFrame frame = new ServerMainFrame();
					frame.setVisible(true);
					frame.setLocationRelativeTo(null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public ServerMainFrame() {
		try {
			UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}
		Font font = new Font("微软雅黑", Font.PLAIN, 12);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 479, 342);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBorder(new EmptyBorder(0, 10, 0, 0));
		contentPane.add(scrollPane, BorderLayout.CENTER);

		elp = new ErrorLogPrinterImpl();
		elp.setFont(font);
		scrollPane.setViewportView(elp);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.WEST);
		panel.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
				ColumnSpec.decode("93px:grow"),},
			new RowSpec[] {
				FormFactory.LINE_GAP_ROWSPEC,
				RowSpec.decode("23px"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,}));

		isServingTF = new JTextField();
		isServingTF.setFont(font);
		isServingTF.setText("服务器已停止");
		isServingTF.setEditable(false);
		panel.add(isServingTF, "2, 4, fill, default");
		isServingTF.setColumns(10);

		JButton btnNewButton_1 = new JButton("导入数据");
		panel.add(btnNewButton_1, "2, 6");
		btnNewButton_1.setFont(font);
		btnNewButton_1.addActionListener(e -> importData());

		JButton btnNewButton_2 = new JButton("藏到托盘");
		panel.add(btnNewButton_2, "2, 8");
		btnNewButton_2.setFont(font);
		btnNewButton_2.addActionListener(e -> hideToTray());

		JButton btnNewButton_3 = new JButton("退出");
		panel.add(btnNewButton_3, "2, 10");
		btnNewButton_3.setFont(font);
		btnNewButton_3.addActionListener(e -> exit());

		JButton btnNewButton = new JButton("开始服务");
		btnNewButton.setFont(font);
		panel.add(btnNewButton, "2, 2");
		
		JButton button = new JButton("爬取数据");
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ImportFromInternetDialog().setVisible(true);
			}
		});
		panel.add(button, "2, 12");
		btnNewButton.addActionListener(e -> startService());

		if (SystemTray.isSupported()) {
			try {
				showTray();
			} catch (AWTException e1) {
				e1.printStackTrace();
			}
		} else {
			btnNewButton_2.setVisible(false);
		}
	}

	private boolean importing = false;

	private void importData() {
		if (importing) {
			JOptionPane.showMessageDialog(this, "数据导入中...");
			return;
		}
		new Thread() {
			@Override
			public void run() {
				JFileChooser fc = new JFileChooser();
				fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int state = fc.showOpenDialog(ServerMainFrame.this);
				if (state == JFileChooser.APPROVE_OPTION) {
					importing = true;
					LocalBLServiceManager.getImportBLService()._import(
							fc.getSelectedFile().getAbsolutePath(), elp);
					importing = false;
				}
			}
		}.start();
	}

	private void showTray() throws AWTException {
		st = SystemTray.getSystemTray();
		Image image = Toolkit.getDefaultToolkit().getImage(
				ServerMainFrame.class.getResource(iconPath));
		TrayIcon ti = new TrayIcon(image);
		ti.setToolTip("SEaC3 NBA信息查询系统服务器");
		ti.addActionListener(e -> this.setVisible(true));
		PopupMenu popup = new PopupMenu();
		MenuItem miexit = new MenuItem("Exit");
		miexit.addActionListener(e -> exit());
		MenuItem mistart = new MenuItem("Start Service");
		mistart.addActionListener(e -> startService());
		MenuItem mishowMain = new MenuItem("Show Main Window");
		mishowMain.addActionListener(e -> this.setVisible(true));
		popup.add(mishowMain);
		popup.add(mistart);
		popup.add(miexit);
		ti.setPopupMenu(popup);
		st.add(ti);
	}

	private void hideToTray() {
		this.dispose();
	}

	private void exit() {
		System.exit(0);
	}

	public void startService() {
		isServingTF.setText("服务器工作中");
		UserMainFrame.main(new String[] { "" });
	}
}
